define(function(require, exports, module) {
	
	var modelTpl=require('resources/template/workflow/model_tpl.html');
	require('resources/js/jquery.dataTables.min.js');
	require('resources/js/jquery.dataTables.bootstrap.js');
	require('resources/js/jquery.dataTables.buttons.js');
	require('resources/js/jquery.json-2.4.min.js');
	require('resources/js/jquery.validate.min.js');
	require('resources/js/jquery.gritter.min.js');
	require('resources/js/ajaxfileupload.js');
	var DTConstant=require('resources/template/common/DTConstant.js');
	var ACEConstant=require('resources/template/common/ACEConstant.js');
	
	var Model=function($container,config,data){
		this.getUrl=Common.getUrl.bind(this);
		this.config=$.extend({},Model.DEFAULT,config);
		this.data=data;
		this.$container=$container;
		this.$div=$(modelTpl).prependTo(this.$container);
		this.init();
	};
	
	var ModelForm=function(parent){
		this.parent=parent;
		this.$div=$('.modelFormModal',parent.$div);
		this.$form=$('.modelForm',parent.$div);
		this.init();
	};
	
	ModelForm.prototype={
		init:function(){
			var that=this;
			//表单验证
			this.formValidator=this.$form.validate($.extend(true,{},ACEConstant.defaultConfig.validate,{
				onsubmit:true,
				rules: {
					name: {
						required: true,
						minlength: 5,
						maxlength: 255
					},
					key: {
						required: true,
						minlength: 5,
						maxlength: 255
					},
					category: {
						maxlength: 255
					}
				},
				submitHandler:function(){
					//获取模型数据
					var data={
							name:$('input[name=name]',that.$form).val(),
							key:$('input[name=key]',that.$form).val(),
							category:$('input[name=category]',that.$form).val(),
							description:$('textarea[name=description]',that.$form).val()							
						},title='创建模型:'+data.name;
					//提交请求 
					$.ajax(that.parent.getUrl('saveModel'),{
						type:'POST',
						dataType:'json',
						data:data
					}).done(function(data){//成功
						if(data.result)
						{
							//刷新list
							that.parent.refreshList();
							//提示成功
							ACEConstant.operateSuccess(title);
							//关掉modal
							that.$div.modal('hide');
							//window.open一个用户设计工作流模型,返回模型id
							that.parent.openModelEditorWindow(data.result);
						}	
						else
							ACEConstant.operateFailed(title,'操作失败：'+data.note);							
					}).fail(function(data){//失败
						//提示失败，
						ACEConstant.operateFailed(title);
					});
				}
			}));
			//保存按钮
			$('.btn-save',this.$div).on('click',function(){
				that.$form.submit();
			});
		},
		show:function(){
			this.clean();
			this.$div.modal({show:true,backdrop:'static'});
		},
		clean:function(){
			$('input,textarea',this.$form).val('');
			$('.form-group',this.$form).removeClass('has-error').removeClass('has-info');
			this.formValidator.resetForm();
		},
		hide:function(){
			this.$div.modal('hide');
		}
	};
	
	Model.prototype={
		urls:{
			list:'/model/list.jhtml',
			saveModel:'/model/save.jhtml',
			deleteModel:'/model/delete.jhtml',
			deployModel:'/model/deploy.jhtml',
			importModel:'/model/import.jhtml',
			viewModel:'/model/view.jhtml?modelId=',
			exportJsonModel:'/model/export.jhtml?type=json&modelId=',
			exportBpmnModel:'/model/export.jhtml?type=bpmn&modelId=',
			modelEditor:'/modeler.html?modelId='
		},	
		init:function(){
			//初始化-列表
			this.initList();
			//初始化-模型弹出框
			this.modelForm=new ModelForm(this);
			//模型流程图查看弹出框
			this.$modelShow=$('.modelShowModal',this.$div);
			this.$modelShowTitle=$('h4',this.$div);
			this.$modelShowImg=$('img',this.$div);
			//导入模型弹出框
			this.initModelImport();
		},
		initModelImport:function(){
			var that=this;
			var tpl='<input multiple="" type="file" class="input-model-file" name="importFile" />'+
                '<label><input type="checkbox" name="file-format" id="id-file-format" class="ace" /></label>';
			this.$modelImport=$('.modelImportModal',this.$div);
			this.$modelImportBody=$('.modal-body',this.$modelImport);
			this.$modelImportBody.append(tpl);
			var initModelFileInput=function(){
				that.$modelImportInput=$('.input-model-file',that.$modelImport);
				that.$modelImportInput.ace_file_input({
					style:'well',
					btn_choose:'请选择或拖放xml|json文件',
					btn_change:null,
					no_icon:'icon-cloud-upload',
					droppable:true,
					thumbnail:'small',
					whitelist:'json|xml',
					before_change:function(files, dropped) {
						var allowed_files = [];
						for(var i = 0 ; i < files.length; i++) {
							var file = files[i];
							if(typeof file === "string") {
								//IE8 and browsers that don't support File Object
								if(! (/\.(json|xml|text)$/i).test(file) ) return false;
							}
							else {
								var type = $.trim(file.type);
								if( ( type.length > 0 &&  !(/\/(json|xml|text)$/i).test(type) )
										|| ( type.length == 0 &&  !(/\.(json|xml|text)$/i).test(file.name) )//for android's default browser which gives an empty string for file.type
									) continue;
							}
							
							allowed_files.push(file);
						}
						if(allowed_files.length == 0) return false;
						return allowed_files;
					}
				});
			};
			initModelFileInput();
			$('.btn-save',this.$modelImport).on('click',function(){
					var now=new Date(),fileId=now.getHours()+'-'+now.getMinutes()+'-'+now.getSeconds();
					that.$modelImportInput.attr('id',fileId);
					$.ajaxFileUpload({
	                    url: that.getUrl('importModel'), //用于文件上传的服务器端请求地址
	                    fileElementId: fileId, //文件上传域的ID
	                    dataType: 'json', //返回值类型 一般设置为json
	                    success: function (data, status){  //服务器成功响应处理函数
	                    	if(data.result)
							{
	                    		//刷新list
								that.refreshList();
								//提示成功
								ACEConstant.operateSuccess('','模型导入成功');
								//关掉modal
								that.$modelImport.modal('hide');
							}	
							else
								ACEConstant.operateFailed(title,'模型导入失败：'+data.note);
	                    	
	                    	that.$modelImportBody.empty();
							that.$modelImportBody.append(tpl);
							initModelFileInput();
	                    },
	                    error: function (data, status, e){//服务器响应失败处理函数
	                    	ACEConstant.operateFailed('','模型导入失败');	
	                    	that.$modelImportBody.empty();
							that.$modelImportBody.append(tpl);
							initModelFileInput();
	                    }
	                });
			});
		},
		showModel:function(model){
			var title='流程模型图:'+model.name;
			this.$modelShowTitle.text(title);
			this.$modelShowImg.attr('alt',title);
			this.$modelShowImg.attr('src',this.getUrl('viewModel')+model.id);
			this.$modelShow.modal('show');
		},
		openModelImport:function(){
			this.$modelImport.modal('show');
		},
		openModelEditorWindow:function(modelId){
			var wprop='top=32,left=32,height=640px,width=1024px,fullscreen=0,directories=0,toolbar=0,titlebar=0,status=0,location=0,channelmode=0,menubar=0,resizable=1,';
			window.open(this.getUrl('modelEditor')+modelId,'_blank',wprop);
		},
		refreshList:function(){
			this.table.ajax.reload();
		},
		initList:function(){
			var that=this;
			this.$list=$('.modelList',this.$div);
			this.table =this.$list.DataTable($.extend(true,{},DTConstant.DEFAULT,{
				ajax:{
				    url:this.getUrl('list'),
				    contentType: "application/json",
				    type: "POST",
				    data: function ( d ) {
				      return $.toJSON(d);
				    }
				},
				rowId:'id',
				columns:[{data:'id',title:''},
				         {data: 'name' ,title:'名称'},
				         {data: 'key' ,title:'标识'},
				         {data: 'category',title:'分类',render:DTConstant.RENDER.ELLIPSIS(35)},
				         {data: 'revision',title:'版本'},
				         {data: 'createTime' ,title:DTConstant.TITLE.DATETIME+'创建时间'},
				         {data: 'lastUpdateTime' ,title:DTConstant.TITLE.DATETIME+'最后更新时间'}
				],
				columnDefs: [DTConstant.COLUMN.RADIO],
				buttons:{
					buttons: [{
						text: '新建',
						className: 'btn btn-sm btn-success icon-lightbulb',
						action: function ( e, dt, node, config ) {
							that.modelForm.show();
						}
					},{
						text: '查看',
						className: 'btn btn-sm btn-success icon-eye-open',
						action: function ( e, dt, node, config ) {
							var record=DTConstant.getSingleRecord(dt)
							if(!record)
								return;
							that.showModel(record);
						}
					},{
						text: '编辑',
						className: 'btn btn-sm btn-success icon-edit',
						action: function ( e, dt, node, config ) {
							var record=DTConstant.getSingleRecord(dt)
							if(!record)
								return;
							that.openModelEditorWindow(record.id);
						}
					},{
						text: '删除',
						className: 'btn btn-sm btn-success icon-trash',
						action: function ( e, dt, node, config ) {
							var record=DTConstant.getSingleRecord(dt)
							if(!record)
								return;
							
							var title='删除模型：'+record.name;
							$.ajax(that.getUrl('deleteModel'),{
								type:'POST',
								dataType:'json',
								data:{modelId:record.id}
							}).done(function(data){//成功
								if(data.result)
								{
									that.refreshList();
									ACEConstant.operateSuccess(title);
								}	
								else
									ACEConstant.operateFailed(title,'操作失败：'+data.note);							
							}).fail(function(data){//失败
								ACEConstant.operateFailed(title);
							});
						}
					},{
						text: '部署',
						className: 'btn btn-sm btn-success icon-beaker',
						action: function ( e, dt, node, config ) {
							var record=DTConstant.getSingleRecord(dt)
							if(!record)
								return;
							
							var title='根据模型部署流程：'+record.name;
							$.ajax(that.getUrl('deployModel'),{
								type:'POST',
								dataType:'json',
								data:{modelId:record.id}
							}).done(function(data){//成功
								if(data.result)
									ACEConstant.operateSuccess(title);
								else
									ACEConstant.operateFailed(title,'操作失败：'+data.note);							
							}).fail(function(data){//失败
								ACEConstant.operateFailed(title);
							});
						}
					},{
						text: '导出',
						className: 'btn btn-sm btn-success icon-external-link',
						action: function ( e, dt, node, config ) {
							var record=DTConstant.getSingleRecord(dt)
							if(!record)
								return;
							window.open(that.getUrl('exportBpmnModel')+record.id);
							window.open(that.getUrl('exportJsonModel')+record.id);
						}
					},{
						text: '导入',
						className: 'btn btn-sm btn-success icon-download-alt',
						action: function ( e, dt, node, config ) {
							that.openModelImport();
						}
					},{
						text: '刷新',
						className: 'btn btn-sm btn-success icon-refresh',
						action: function ( e, dt, node, config ) {
							that.refreshList();
						}
					}]
				}
			}));
			DTConstant.enableRadio(this.$list);
		},
		destroy:function(){
			this.$div.remove();
			this.$vmId&&delete avalon.vmodels[this.$vmId];
		}
	}
	
	Model.DEFAULT={
			
	};
	
	return Model;
});